#!/usr/bin/env python3
"""
启动服务并测试 HTTP API
"""

import subprocess
import time
import asyncio
import httpx
import sys
import os


def start_server():
    """启动服务器"""
    print("🚀 启动 IoT MCP 服务器...")
    
    try:
        # 启动服务器进程
        process = subprocess.Popen(
            [sys.executable, "main.py"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        
        # 等待服务器启动
        print("⏳ 等待服务器启动...")
        time.sleep(5)  # 等待 5 秒
        
        # 检查进程是否还在运行
        if process.poll() is None:
            print("✅ 服务器启动成功!")
            return process
        else:
            stdout, stderr = process.communicate()
            print(f"❌ 服务器启动失败:")
            print(f"   标准输出: {stdout}")
            print(f"   错误输出: {stderr}")
            return None
            
    except Exception as e:
        print(f"❌ 启动服务器时发生错误: {e}")
        return None


async def test_api():
    """测试 API"""
    print("\n🧪 开始测试 HTTP API...")
    
    test_cases = [
        {
            "name": "获取运行中的设备",
            "params": {"state": "运行中"}
        },
        {
            "name": "获取 4#411 场地的设备",
            "params": {"place_name": "4#411"}
        },
        {
            "name": "获取照明类型的设备",
            "params": {"device_type": "照明"}
        }
    ]
    
    async with httpx.AsyncClient(timeout=10.0) as client:
        for i, test_case in enumerate(test_cases, 1):
            print(f"\n📋 测试 {i}: {test_case['name']}")
            print(f"   参数: {test_case['params']}")
            
            try:
                response = await client.get(
                    "http://localhost:8000/api/devices",
                    params=test_case['params']
                )
                
                if response.status_code == 200:
                    data = response.json()
                    print(f"   ✅ 成功! 找到 {data['count']} 个设备")
                    
                    # 显示前几个设备
                    for device in data['devices'][:2]:
                        print(f"      - {device['device_name']} ({device['device_type']}) - {device['place_name']}")
                    
                    if len(data['devices']) > 2:
                        print(f"      ... 还有 {len(data['devices']) - 2} 个设备")
                        
                else:
                    print(f"   ❌ 失败! 状态码: {response.status_code}")
                    print(f"      错误: {response.text}")
                    
            except httpx.ConnectError:
                print("   ❌ 连接失败: 服务器可能还未完全启动")
            except Exception as e:
                print(f"   ❌ 错误: {e}")
    
    print("\n🎉 API 测试完成!")


async def main():
    """主函数"""
    print("🔧 IoT MCP 服务器启动和测试脚本")
    print("=" * 60)
    
    # 启动服务器
    server_process = start_server()
    if not server_process:
        print("❌ 无法启动服务器，退出")
        return
    
    try:
        # 等待一段时间让服务器完全启动
        print("⏳ 等待服务器完全启动...")
        time.sleep(3)
        
        # 测试 API
        await test_api()
        
        print("\n💡 提示:")
        print("   - 服务器正在后台运行")
        print("   - 访问 http://localhost:8000/docs 查看 API 文档")
        print("   - 按 Ctrl+C 停止服务器")
        
        # 保持服务器运行
        while True:
            time.sleep(1)
            
    except KeyboardInterrupt:
        print("\n\n⏹️ 用户中断，正在停止服务器...")
    except Exception as e:
        print(f"\n❌ 发生错误: {e}")
    finally:
        # 停止服务器
        if server_process:
            print("🛑 停止服务器...")
            server_process.terminate()
            server_process.wait()
            print("✅ 服务器已停止")


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\n⏹️ 脚本被用户中断")
    except Exception as e:
        print(f"\n❌ 脚本执行失败: {e}")
